package cn.lijiajia3515.cairo.system.modules.file;

import cn.lijiajia3515.cairo.core.page.Page;
import cn.lijiajia3515.cairo.security.oauth2.jwt.CairoJwtPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

@Slf4j
@Validated
@RestController
@RequestMapping("/file/folder")
public class FolderApi {
	private final FolderService folderService;

	public FolderApi(FolderService folderService) {
		this.folderService = folderService;
	}

	@PostMapping("/save")
	@PreAuthorize("isAuthenticated()")
	public Optional<Folder> save(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody @Valid @Validated SaveFolderParam param) {
		String client = principal.getClient();
		return folderService.save(client, param);
	}

	@PatchMapping("/rename")
	@PreAuthorize("isAuthenticated()")
	public Optional<Folder> put(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody @Valid @Validated RenameFolderParam param) {
		String client = principal.getClient();
		return folderService.rename(client, param);
	}

	@DeleteMapping("/delete")
	@PreAuthorize("isAuthenticated()")
	public List<Folder> delete(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody @Valid @Validated DeleteFolderParam param) {
		String client = principal.getClient();
		return folderService.delete(client, param);
	}

	@PostMapping("/find")
	@PreAuthorize("isAuthenticated()")
	public Page<Folder> find(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody @Valid @Validated FindFolderParam param) {
		String client = principal.getClient();
		return folderService.findPage(client, param);
	}

	@PostMapping("/find_page")
	@PreAuthorize("isAuthenticated()")
	public Page<Folder> findPage(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody @Valid @Validated FindFolderParam param) {
		String client = principal.getClient();
		return folderService.findPage(client, param);
	}

	@PostMapping("/find_tree")
	@PreAuthorize("isAuthenticated()")
	public List<Folder> treeFind(@AuthenticationPrincipal CairoJwtPrincipal principal, @RequestBody @Valid @Validated FindFolderParam param) {
		String client = principal.getClient();
		return folderService.findTree(client, param);
	}
}
